package com.xuyiwei.mayi.test;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.util.StringUtils;

import java.io.File;
import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.List;

/**
 * Created by xuyiwei on 2019/4/13.
 */
public class IOCUtils {
    public UserIoc getIoc(String id) throws DocumentException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {
        if (StringUtils.isEmpty(id)) {
            return null;
        }
        Object object = null;
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File("/Users/xuyiwei/Downloads/mayitest/springioc/src/main/java/com/xuyiwei/mayi/test/User.xml"));
        Element root = document.getRootElement();
        Iterator<Element> it = root.elementIterator();
        while (it.hasNext()) {
            Element e = it.next();
            Attribute idAttr = e.attribute("id");
            String value = idAttr.getValue();
            if (id.equals(value)) {
                Attribute classAttr = e.attribute("class");
                String classValue = classAttr.getValue();
                Class c = Class.forName(classValue);
                object = c.newInstance();
                //得到下属节点
                Iterator<Element> childEles = e.elementIterator();
                while (childEles.hasNext()) {
                    Element child = childEles.next();
                    String fileName = child.attribute("name").getValue();
                    Field field = c.getDeclaredField(fileName);
                    field.setAccessible(true);
                    String fileValue = child.attribute("value").getValue();
                    field.set(object,fileValue);

                }
            }

        }
        return (UserIoc) object;
    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, InstantiationException, DocumentException, IllegalAccessException {
        IOCUtils utils = new IOCUtils();
        UserIoc u = utils.getIoc("user1");
        System.out.println(u);
    }
}
